import React from 'react'
import {log} from "../../utils/commonfunc";
import './forecast.css'
import bannerSrc from "../../res/images/web/vote/活动模版／黄色2@2x.png";
import Rate from "../GradePlayer/rate/rate";
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import {getVoteResultReq, voteForecastReq} from "../../apis/goApis";
import LocalStorageService from "../../utils/LocalStorageService";
import {Modal, Toast} from "antd-mobile";
import reloadSrc from "../../res/images/web/vote/更新@2x.png"
import VoteGobackTab from "../GradePlayer/vote-goback-tab/vote-goback-tab";
import {checkAndGoBack} from "../best-line-up/best-line-up";
import {onTaskDone} from "../plan-detail/plan-detail";
import {test} from "../../utils/constants";
import {addLinkAndClick} from "../GradePlayer/GradePlayer";

class Forecast extends React.Component {
    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.voteId = parseInt(this.props.match.params.id)
        this.state = {
            options: [],
            result: [],
            myOption: '',
            total: 0,
            flag: 0,
            optionIndex: -1,
            offset: 0,
            voted: false,
            event: '',
            title: '',
            fetchBannerFinished: false,
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {
        const params = this.searchParams()
        const webview = params.webview
        if (webview === 'true') {
            log('webview')
            this.uid = params.uid
            this.setState({
                webview: true,
            }, () => this.detail())
        } else {
            this.detail()
        }
    }

    searchParams = () => {
        const search = window.location.search
            .slice(1)
            .split('&')
            .map(keyValue => {
                return keyValue.split('=')
            })
            .reduce((acc, cur) => {
                acc[cur[0]] = cur[1]
                return acc
            }, {})
        return search
    }


    detail = () => {
        const params = {
            Uid: this.uid,
            Sid: parseInt(this.props.match.params.id),
            Flag: 3,
        }
        log(params)
        getVoteResultReq(params).then(res => {
            const data = res.data.ok
            const sr = res.data.sr
            if (sr) {
                log(sr)
                const result = res.data.ok
                const data = sr
                const count = result.reduce((acc, cur) => {
                    acc += cur.Count
                    return acc
                },0)
                this.setState({
                    voted: true,
                    event: data.Match,
                    title: data.Title,
                    flag: data.Stype,
                    result: result,
                    total: count,
                    myOption: data.Option,
                }, () => this.more())
            } else if (data) {
                log(data)
                if (data) {
                    this.setState({
                        event: data.Match,
                        title: data.Title,
                        options: data.Option,
                        flag: data.Stype,
                    })
                }
            }

        })
    }

    submit = () => {
        const optionIndex = this.state.optionIndex
        const selected = optionIndex > -1
        if (selected) {
            const params = {
                Uid: this.uid,
                Sid: this.voteId,
                Option: this.state.options[optionIndex + this.state.offset].Op,
            }
            log(params)
            voteForecastReq(params)
                .then((res) => {
                    const data = res.data
                    if (data.ok) {
                        this.done()
                    }
                })
                .then(() => this.detail())
        }

    }

    done = () => {
        const uid = this.state.webview ? this.searchParams().uid : this.uid
        onTaskDone(uid, 'ltft')
            .then(data => {
                if (data.Code === 0) {
                    this.setState({
                        taskDone: true,
                        taskInfo: data.Msg,
                    })
                }
            })
    }

    more = () => {
        const webview = this.state.webview
        const end = test ? 'http://test.youtoball.com:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'
        const btnList = [
            {
                text: <span>下次再做</span>,
                onPress: () => {},
            },
            {
                // text: webview
                //     ? <span style={{color: '#FFA500',}}>去做任务</span>
                //     : <a href={end}><span style={{color: '#FFA500',}}>去做任务</span></a>,
                text: <span style={{color: '#FFA500',}}>去做任务</span>,
                onPress: webview
                    ? () => addLinkAndClick(end)
                    : () => this.props.history.push('../../../ren_wu'),
            },
        ]
        Modal.alert(
            <span
                style={{
                    fontSize: '16px',
                    fontWeight: 500,
                    color: '#333333',
                    lineHeight: '22px',
                }}
            >'完成每日任务，可获得更多球星红包和奖励</span>,
            '合成球星越多，收益越多',
            btnList
        )
    }

    reloadOptions = () => {
        const offset = this.state.offset
        let next = offset + 6
        if (next > this.state.options.length - 1) {
            next = 0
        }
        this.setState({
            optionIndex: -1,
            offset: next,
        })
    }

    render() {
        const options = this.state.options
        const optionIndex = this.state.optionIndex
        const offset = this.state.offset
        const selected = optionIndex > -1
        const voted = this.state.voted

        const voteButton = <div className='grade-player-button fade-in'>
            <CustomButton
                color={selected ? '#fff' : 'rgba(51, 51, 51, 0.4)'}
                bg={selected ? '#FFA500' : '#E6E6E6'}
                onClick={() => this.submit()}
            >
                提交
            </CustomButton>
        </div>

        const mainTemplate = <div className='grade-player-container fade-in'>
            <div className='grade-player-event forecast-event'>
                <p>{this.state.event}</p>
            </div>
            <p className='forecast-title'>
                {this.state.title}
            </p>
            {voted === false && options.length === 2 && options.map((option, index) => {
                log("option", option)
                const selected = index === optionIndex
                return <div
                    className='forecast-option-item flex-align-center'
                    key={index}
                    style={{
                        border: selected ? '2px solid #0070DF' : '',
                    }}
                    onClick={() => {
                        this.setState({
                            optionIndex: index,
                        })
                    }}
                >
                    <p>{option.Op}</p>
                </div>
            })}
            {voted === false && options.length > 2 && <div className='flex-space-between flex-wrap-container'>
                {options.slice(offset, offset + 6).map((option, index) => {
                    const selected = index === optionIndex
                    return <div
                        className='forecast-option-item flex-align-center'
                        key={index}
                        style={{
                            width: '49%',
                            border: selected ? '2px solid #0070DF' : '',
                        }}
                        onClick={() => {
                            this.setState({
                                optionIndex: index,
                            })
                        }}
                    >
                        <p>{option.Op}</p>
                    </div>
                })}
            </div>}
            {this.state.voted && <div className='fade-in'>
                <p className='mg-b-24px'>我选择了"{this.state.myOption}"</p>
                <div
                    style={{
                        maxHeight: window.innerHeight - this.banner.height - 73 - 38 - 48 - 24,
                        overflowY: 'scroll',
                    }}
                >
                    {this.state.result.map((value, index) => {
                        const per = ((value.Count / this.state.total) * 100).toFixed(2)
                        return <div key={index} >
                            <div className='flex-space-between pd-8px'>
                                <p>{value.Option}</p>
                                <p style={{color: '#FF8300',}}>{per}%的人选了</p>
                            </div>

                            <div
                                style={{
                                    width: '100%',
                                    height: '10px',
                                    borderRadius: '5px',
                                    background: '#FFEECF',
                                    position: 'relative',
                                }}
                            >
                                <div style={{
                                    width: `${per}%`,
                                    height: '10px',
                                    borderRadius: '5px',
                                    background: '#FFA500',
                                    top: '0',
                                    left: '0',
                                }}/>
                            </div>
                        </div>
                    })}
                </div>
            </div>}
            {voted === false && options.length > 7 && <div>
                <CustomButton
                    bg='#fff'
                    color='#0070DF'
                    // extrastyle={{
                    //     border: '2px solid #0070DF',
                    // }}
                    onClick={() => this.reloadOptions()}
                >
                    <div className='flex-center-align-center'>
                        <img src={reloadSrc} alt='' style={{width: 18, height: 18, marginRight: '4px'}}/>
                        <span>换一波</span>
                    </div>
                </CustomButton>
            </div>}

        </div>
        return (
            <div className='grade-container forecast-container'>
                <VoteGobackTab
                    title='预测'
                    goBack={() => checkAndGoBack(this.props.history, '../../../vote-list/forecast')}

                    color='#fff'
                />
                <img
                    src={bannerSrc}
                    alt=''
                    style={{width: '100%', height: 'auto',}}
                    onLoad={() => {
                        this.setState({
                            fetchBannerFinished: true,
                        })
                    }}
                    ref={el => this.banner = el}
                />
                {this.state.fetchBannerFinished && mainTemplate}

                {voted === false && this.state.fetchBannerFinished && <p className='forecast-desc fade-in'>大家都选了谁？完成预测即可查看</p>}

                {voted === false && this.state.fetchBannerFinished && voteButton}
            </div>
        )
    }

}

export default Forecast